import { createRouter, createWebHistory } from "vue-router"


const routes = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/login',
    name: '登录',
    component: () => import('../views/Login.vue')
  },
  {
    path: '/register',
    name: '注册',
    component: () => import('../views/Register.vue')
  },
  {
    path: '/home',
    name: '首页',
    component: () => import('../views/Home.vue')
  },
  {
    path: '/menu',
    name: '菜单',
    component: () => import('../views/Menu.vue'),
  },
  {
    path: '/cart',
    name: '购物车',
    component: () => import('../views/Cart.vue'),
    meta: { requiresAuth: true },   // 此字段用于身份验证，该页需要登录才可访问
  },
  {
    path: '/user',
    name: '我的',
    meta: { requiresAuth: true },   // 此字段用于身份验证，该页需要登录才可访问
    component: () => import('../views/User.vue')
  },
   //用户头像
   {path:'/smblack',component:()=>import('../views/smblack.vue')},
  //售后/退款
  {path:'/refund',component:()=>import('../views/refund.vue')},
  //地址管理
  {path:'/address',component:()=>import('../views/address.vue')},
  //昵称
  {path:'/rename',component:()=>import('../views/rename.vue')},
  //修改号码
  {path:'/phone',component:()=>import('../views/phone.vue')},
  //全部订单
  {path:'/list',component:()=>import('../views/list.vue')},
  //待收货
    {path:'/receipt',component:()=>import('../views/receipt.vue')},
  //待自提
    {path:'/pickup',component:()=>import('../views/pickup.vue')},
  //待付款
  {path:'/payfor',component:()=>import('../views/payfor.vue')},
  // 新增地址
  {path:'/newadd',component:()=>import('../views/newadd.vue')},
  // 商品详情页
  {
    path: `/goods/:goodsId`,
    name: 'GoodsDetail',
    component: () => import('../views/GoodsDetail.vue')
  },
  // 订单页
  {
    path: '/order',
    name: 'Order',
    component: () => import('../views/Order.vue')
  },
  // 搜索页
  {
    path: '/search',
    name: 'Search',
    component: () => import('../views/Search.vue')
  },
  {
    path: '/:catchAll(.*)', // 匹配所有未知路由
    name: '未设置路由的其他页面',
    component: () => import('../views/404.vue')
  },
]

const router = createRouter({
  routes,
  history: createWebHistory()
})

// 路由导航守卫
router.beforeEach((to, from, next) => {
  // 检查 seesionStorage 中是否存在 userInfo
  const token = sessionStorage.getItem('userInfo')
  if (to.meta.requiresAuth && !token) {
    // 若当前路由需要登录才可访问且用户不处于登录状态，提示用户“权限不足，请先登录”，并跳转到登录页
    next('/login')
  } else {
    next()
  }
})

export default router